package models

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

type User struct {
	Id         int
	UserName   string
	Password   string
	Token      string
	Profile    *Profile   `orm:"null;rel(one);on_delete(set_null)"` // OneToOne relation
	Assets     []*Assets  `orm:"rel(m2m)"`
	Routers    []*Routers `orm:"rel(m2m)"`
	IsDelete   int        `orm:"default(0)"`
	CreateTime time.Time  `orm:"auto_now_add;type(datetime)"`
	UpdateTime time.Time  `orm:"auto_now;type(datetime)"`
}

type Profile struct {
	Id   int
	Age  int16
	Sex  int
	User *User `orm:"reverse(one)"` // 设置一对一反向关系(可选)
	Info string
}

type Assets struct {
	Id         int
	AssetsName string
	User       []*User `orm:"reverse(many)"`
}

type Routers struct {
	Id              int		`json:"id"`
	Pid             int		`json:"pid"`
	RouterTitle     string	`json:"routerTitle"`
	RouterPath      string	`json:"routerPath"`
	RouterName      string	`json:"routerName"`
	RouterComponent string	`json:"routerComponent"`
	User            []*User `orm:"reverse(many)";json:"user"`
}

/**
登录
*/
func Login(username string, password string) (error, User) {
	o := orm.NewOrm()
	user := User{}
	err := o.QueryTable("user").Filter("UserName", username).Filter("Password", password).One(&user)
	return err, user
}

/**
更新用户token
*/
func SetToken(id int, token string) error {
	o := orm.NewOrm()
	user := User{Id: id, Token: token}
	_, err := o.Update(&user, "token")
	return err
}

/**
获取用户菜单
*/
func GetUserMenus(userId int) []*Routers {
	o := orm.NewOrm()
	menus := []*Routers{}
	_, err := o.QueryTable("routers").Filter("User__User__Id", userId).All(&menus)
	if err != nil {
		fmt.Println(err)
	}
	for _, value := range menus {
		fmt.Printf("%+v", value)
	}
	return menus

}

func init() {
	// 数据库配置项
	driverName := beego.AppConfig.String("driverName")
	user := beego.AppConfig.String("mysqlUser")
	password := beego.AppConfig.String("mysqlPwd")
	host := beego.AppConfig.String("host")
	port := beego.AppConfig.String("port")
	dbName := beego.AppConfig.String("dbName")
	// 数据库连接
	dbConn := user + ":" + password + "@tcp(" + host + ":" + port + ")/" + dbName + "?charset=utf8"
	err := orm.RegisterDataBase("default", driverName, dbConn)
	if err != nil {
		fmt.Println("数据库连接出错")
		return
	}
	fmt.Println("连接成功")
	orm.RegisterModel(new(User), new(Profile), new(Assets), new(Routers))
	orm.RunSyncdb("default", false, true)
}
